import Foundation
import Vapor
import Fluent
import Redis

struct AvatarUploadController {
    // 处理预签名URL请求
    @Sendable
    func getUploadURL(req: Request) async throws -> AvatarUploadResponse {
        // 验证用户身份
        let userID = try req.authenticatedUserID
        
        // 解析请求数据
        struct UploadRequest: Content {
            let fileExtension: String
            let contentType: String
            let contentMD5: String?
        }
        
        let uploadRequest = try req.content.decode(UploadRequest.self)
        
        // 验证文件扩展名
        guard ["jpg", "jpeg", "png", "gif", "webp"].contains(uploadRequest.fileExtension.lowercased()) else {
            throw Abort(.badRequest, reason: "不支持的文件类型，仅支持jpg、jpeg、png、gif和webp格式")
        }
        
        // 验证内容类型
        guard uploadRequest.contentType.hasPrefix("image/") else {
            throw Abort(.badRequest, reason: "非法的内容类型，必须是图片类型")
        }
        
        // 生成唯一的文件名 - 使用微服务API
        let fileName = try await req.cosServiceProxy.generateUniqueFileName(
            userId: userID,
            fileExtension: uploadRequest.fileExtension
        )
        
        // 生成预签名上传URL - 使用微服务API
        let uploadURL = try await req.cosServiceProxy.generatePresignedUrl(
            for: fileName,
            fileType: uploadRequest.contentType,
            contentMD5: uploadRequest.contentMD5,
            expiresIn: 3600
        )
        
        // 构建文件完整路径
        let filePath = "avatar/\(fileName)"
        
        var instructions = "使用PUT方法上传文件，必须设置Content-Type请求头为指定的contentType值"
        if uploadRequest.contentMD5 != nil {
            instructions += "，并设置Content-MD5请求头为提供的contentMD5值"
        }
        
        return AvatarUploadResponse(
            uploadURL: uploadURL,
            fileName: fileName,
            filePath: filePath,
            contentType: uploadRequest.contentType,
            contentMD5: uploadRequest.contentMD5,
            expiresIn: 3600,
            uploadInstructions: instructions
        )
    }
    
    // 处理上传确认和头像更新
    @Sendable
    func confirmUpload(req: Request) async throws -> AvatarConfirmResponse {
        // 验证用户身份
        let userID = try req.authenticatedUserID
        
        // 解析请求数据
        struct ConfirmRequest: Content {
            let filePath: String
            let uploadSuccessful: Bool
            let size: String?  // 可选参数，指定头像尺寸
        }
        
        let confirmRequest = try req.content.decode(ConfirmRequest.self)
        
        // 检查上传是否成功
        guard confirmRequest.uploadSuccessful else {
            throw Abort(.badRequest, reason: "文件上传失败，请重试")
        }
        
        // 验证文件路径
        guard confirmRequest.filePath.starts(with: "avatar/") else {
            throw Abort(.badRequest, reason: "无效的文件路径")
        }
        
        // 检查用户是否存在
        guard let user = try await User.find(userID, on: req.db) else {
            throw Abort(.notFound, reason: "用户不存在")
        }
        
        // 处理头像并获取多种尺寸 - 使用微服务API
        let avatarResult = try await req.cosServiceProxy.processAvatar(
            for: confirmRequest.filePath,
            size: confirmRequest.size
        )
        
        // 更新用户头像
        user.avatar = confirmRequest.filePath
        try await user.save(on: req.db)
        
        // 清除用户缓存，确保其他请求能获取到最新头像
        let cacheKey = RedisKey("user:\(userID)")
      let _ = req.redis.delete(cacheKey)
        
        return AvatarConfirmResponse(
            success: true,
            message: "头像更新成功",
            avatarUrl: avatarResult.avatarUrl,
            avatarUrls: avatarResult.avatarUrls
        )
    }
    
    // 裁剪头像
    @Sendable
    func cropAvatar(req: Request) async throws -> AvatarConfirmResponse {
        // 验证用户身份
        let userID = try req.authenticatedUserID
        
        // 解析请求数据
        struct CropRequest: Content {
            let avatarKey: String
            let cropRegion: [String: Int]
            let targetSize: Int?
            let rotate: Int? // 添加旋转角度参数
        }
        
        let cropRequest = try req.content.decode(CropRequest.self)
        
        // 验证文件路径
        var avatarKey = cropRequest.avatarKey
        if !avatarKey.starts(with: "avatar/") {
            avatarKey = "avatar/\(avatarKey)"
        }
        
        // 检查用户是否存在
        guard let user = try await User.find(userID, on: req.db) else {
            throw Abort(.notFound, reason: "用户不存在")
        }
        
        // 裁剪头像 - 使用微服务API
        var cropResult: AvatarCropResult
        
        // 如果有旋转角度参数，则传递
        if let rotateAngle = cropRequest.rotate, rotateAngle != 0 {
            // 传递旋转角度
            cropResult = try await req.cosServiceProxy.cropAvatar(
                for: avatarKey,
                cropRegion: cropRequest.cropRegion,
                targetSize: cropRequest.targetSize,
                rotate: rotateAngle
            )
        } else {
            // 原有的裁剪逻辑
            cropResult = try await req.cosServiceProxy.cropAvatar(
                for: avatarKey,
                cropRegion: cropRequest.cropRegion,
                targetSize: cropRequest.targetSize
            )
        }
        
        // 清除用户缓存
        let cacheKey = RedisKey("user:\(userID)")
        let _ = req.redis.delete(cacheKey)
        
        return AvatarConfirmResponse(
            success: cropResult.success,
            message: cropResult.message,
            avatarUrl: cropResult.avatarUrl,
            avatarUrls: cropResult.avatarUrls
        )
    }
    
    // 旋转头像
    @Sendable
    func rotateAvatar(req: Request) async throws -> AvatarConfirmResponse {
        // 验证用户身份
        let userID = try req.authenticatedUserID
        
        // 解析请求数据
        struct RotateRequest: Content {
            let avatarKey: String
            let angle: Int
            let targetSize: Int?
        }
        
        let rotateRequest = try req.content.decode(RotateRequest.self)
        
        // 验证文件路径
        var avatarKey = rotateRequest.avatarKey
        if !avatarKey.starts(with: "avatar/") {
            avatarKey = "avatar/\(avatarKey)"
        }
        
        // 检查用户是否存在
        guard let user = try await User.find(userID, on: req.db) else {
            throw Abort(.notFound, reason: "用户不存在")
        }
        
        // 旋转头像 - 使用微服务API
        let rotateResult = try await req.cosServiceProxy.rotateAvatar(
            for: avatarKey,
            angle: rotateRequest.angle,
            targetSize: rotateRequest.targetSize
        )
        
        // 清除用户缓存
        let cacheKey = RedisKey("user:\(userID)")
        let _ = req.redis.delete(cacheKey)
        
        return AvatarConfirmResponse(
            success: rotateResult.success,
            message: rotateResult.message,
            avatarUrl: rotateResult.avatarUrl,
            avatarUrls: rotateResult.avatarUrls
        )
    }
}

// 响应结构
struct AvatarUploadResponse: Content {
    let uploadURL: String
    let fileName: String
    let filePath: String
    let contentType: String
    let contentMD5: String?
    let expiresIn: Int
    let uploadInstructions: String
}

// 头像确认响应
struct AvatarConfirmResponse: Content {
    let success: Bool
    let message: String
    let avatarUrl: String
    let avatarUrls: [String: String]?
} 
